<template>
    <show-modal :title="title" :loading="loading" width="540px" @cancel="cancel" :isCancel="true" :isReset="false"
        :isSure="false">
        <template v-if="previewUrl.indexOf('.pdf') > 0">
            <pdf ref="pdf" :src="previewUrl" v-for="i in pdfPages" :key="i" :page="i" style="width:100%;" />
        </template>
        <template v-else-if="previewUrl.indexOf('mp4') > 0">
            <video ref="video" width="500" controls autoplay>
                <source :src="previewUrl" type="video/mp4" />
            </video>
        </template>
        <template v-else>
            <img class="image" :src="previewUrl" />
        </template>
    </show-modal>
</template>
<script>
import pdf from 'vue-pdf';
export default {
    name: 'ShowPreview',
    components: {
        pdf
    },
    props: {
        info: {
            type: Object,
            default: () => { }
        },
        urlType:{
            type:String,
            default:'mtUrl'
        },
        name:{
            type:String,
            default:'mtUrl'
        }
    },
    data() {
        return {
            title: '预览',
            loading: false,
            previewUrl: '',
            pdfPages: null
        };
    },
    created() {
        this.title = this.info[this.name];
        this.previewUrl = this.info[this.urlType];
        if (this.previewUrl.indexOf('.pdf') > 0) {
            this.getPdfPages(this.previewUrl);
        }
    },
    methods: {
        cancel() {
            this.$emit('cancel');
        },
        //获取pdf页数
        getPdfPages(url) {
            let loadingTask = pdf.createLoadingTask(url);
            loadingTask.promise
                .then(res => {
                    this.pdfPages = res.numPages;
                })
                .catch(err => {
                    console.log('加载失败：' + err);
                });
        }
    },
    beforeDestroy() {
        let video = this.$refs.video;
        if (video) {
            video.pause();
        }
    }
};
</script>
<style lang="scss" scoped>
.image {
    width: 100%;
}
</style>
